<template>
  <Layer :layer="layer" @confirm="submit" ref="layerDom">
    <el-form :model="form" :rules="rules" ref="ruleForm" label-width="120px" style="margin-right: 30px">
      <el-form-item label="标签" prop="label">
        <el-input v-model="form.label" placeholder="请输入标签"></el-input>
      </el-form-item>
      <el-form-item label="值" prop="value">
        <el-input v-model="form.value" placeholder="请输入标签值">
        </el-input>
      </el-form-item>
      <el-form-item label="菜单排序" prop="dictSort">
        <el-input-number size="small" v-model.number="form.dictSort" :min="0" :max="999" controls-position="right"
                         style="width: 178px;"/>
      </el-form-item>
      <el-form-item label="菜单状态" prop="status">
        <el-radio-group v-model="form.status" size="small" style="width: 178px">
          <el-radio-button label="false">关闭</el-radio-button>
          <el-radio-button label="true">显示</el-radio-button>
        </el-radio-group>
      </el-form-item>
    </el-form>
  </Layer>
</template>

<script lang="ts" setup>
import type {LayerType} from "@/components/layer/index.vue";
import {inject, Ref} from "vue";
import type {ElFormItemContext} from "element-plus/lib/el-form/src/token";
import {ref} from "vue";
import {addDetail, updateDetail} from "@/api/system/dict";
import Layer from "@/components/layer/index.vue";
import {ElMessage} from "element-plus";

const props = defineProps({
  layer: {
    type: Object,
    default() {
      return {
        show: false,
        title: "",
        showButton: true,
      };
    },
  },
});
const ruleForm: Ref<ElFormItemContext | null> = ref(null);
const layerDom: Ref<LayerType | null> = ref(null);
const emits = defineEmits(["getTableData"]);
const active: any = inject("active");
let form = ref({
  label: "",
  value: "",
  status: true,
  dictSort: 10,
});
const rules = {
  label: [{required: true, message: "请输入标签", trigger: "blur"}],
  value: [{required: true, message: "请输入标签值", trigger: "blur"}],
};
init();

function init() {
  // 用于判断新增还是编辑功能
  if (props.layer.row) {
    form.value = JSON.parse(JSON.stringify(props.layer.row)); // 数量量少的直接使用这个转
  } else {
  }
}

const submit = () => {
  ruleForm.value.validate((valid: boolean) => {
    if (valid) {
      let params = form.value;
      if (props.layer.row) {
        updateForm(params);
      } else {
        addForm(params);
      }
    } else {
      return false;
    }
  });
};
// 新增提交事件
const addForm = (params: object) => {
  params = {
    dictId: active.value,
    ...params
  }
  console.log(form.value)
  addDetail(params).then((res) => {
    ElMessage({
      type: "success",
      message: "新增成功",
    });
    props.layer.show = false;
    emits("getTableData", true);
  });
};

// 编辑提交事件
const updateForm = (params: object) => {
  updateDetail(params).then((res) => {
    ElMessage({
      type: "success",
      message: "编辑成功",
    });
    emits("getTableData", false);
  });
};
</script>

<style lang="scss" scoped>
</style>